#include "Semaphore.h"

Semaphore::Semaphore(char* file, int initialValue) {
	this->initialValue = initialValue;

	key_t key = ftok(file, 'a');
	this->id = semget(key, 1, 0666 | IPC_CREAT );

	this->initialize();
}

Semaphore::~Semaphore() {
}

int Semaphore::initialize() {
	union semnum {
		int val;
		struct semid_ds* buf;
		ushort* array;
	};

	semnum init;
	init.val = this->initialValue;
	int result = semctl(this->id, 0, SETVAL, init);
	return result;
}

int Semaphore::p() {
	struct sembuf operation;

	operation.sem_num = 0;	// numero de semaforo
	operation.sem_op  = -1;	// restar 1 al semaforo
	operation.sem_flg = SEM_UNDO;

	int result = semop( this->id, &operation, 1);
	return result;
}

int Semaphore::v() {
	struct sembuf operation;

	operation.sem_num = 0;	// numero de semaforo
	operation.sem_op  = 1;	// sumar 1 al semaforo
	operation.sem_flg = SEM_UNDO;

	int result = semop(this->id, &operation, 1);
	return result;
}

void Semaphore::destroy() {
	semctl(this->id, 0, IPC_RMID);
}
